package org.ncibi.cytoscape.metscape.task;

import org.ncibi.cytoscape.metscape.plugin.PluginRegistration;
import org.ncibi.ws.HttpRequestType;
import org.ncibi.ws.Response;
import org.ncibi.metab.ws.client.MetabolicRegistrationService;

import cytoscape.Cytoscape;
import cytoscape.task.Task;
import cytoscape.task.TaskMonitor;
import cytoscape.task.ui.JTaskConfig;
import cytoscape.task.util.TaskManager;

public class RecordRegistrationTask implements Task {

	private TaskMonitor taskMonitor;
	private boolean interrupted = false;
	private final PluginRegistration registrationRecord;

	public static void recordRegistration(PluginRegistration registrationRecord) {
		RecordRegistrationTask task = new RecordRegistrationTask(registrationRecord);
		configureAndRunTask(task);
	}
	
	public RecordRegistrationTask(PluginRegistration registrationRecord) {
		this.registrationRecord = registrationRecord;
	}
	
	private static void configureAndRunTask(RecordRegistrationTask task) {
		// Configure JTask Dialog Pop-Up Box
		JTaskConfig jTaskConfig = new JTaskConfig();
		jTaskConfig.setOwner(Cytoscape.getDesktop());
		jTaskConfig.displayCancelButton(true);
		jTaskConfig.displayStatus(true);

		// Execute Task in New Thread; pops open JTask Dialog Box.
		TaskManager.executeTask(task, jTaskConfig);
	}

	public void setTaskMonitor(TaskMonitor monitor)
			throws IllegalThreadStateException {
		taskMonitor = monitor;
	}

	public void halt() {
		interrupted = true;
	}

	public String getTitle() {
		return "Saving registration data";
	}

	public void run() {
		try {
			taskMonitor.setPercentCompleted(-1);
			taskMonitor.setStatus("Saving registration data...");

			Response<Boolean> serverResponse;
			MetabolicRegistrationService service = new MetabolicRegistrationService(
					HttpRequestType.POST);
			System.out.println("Making registration server request");
			serverResponse = service.register(registrationRecord.getDataForServer());
			boolean registered = false;
			if (serverResponse != null) {
				boolean success = serverResponse.getResponseStatus().isSuccess();
				registered = (success)?serverResponse.getResponseValue().booleanValue():false;
				if (registered)
					registrationRecord.markAsRegistered();
				System.out.println("Server registration request was returned; success = " + success + "; registered = " + registered);
			}
			taskMonitor.setStatus("Complete");
			taskMonitor.setPercentCompleted(100);

		} catch (Throwable t) {
			if (!interrupted)
				taskMonitor.setException(t, "Save failed (server unavailable)");
		}

	}
}
